package com.competition.controller;

import com.competition.resp.ResponseResult;
import com.competition.utils.plant.Base64Util;
import com.competition.utils.plant.FileUtil;
import com.competition.utils.plant.HttpUtil;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/plant")
public class PlantRecognitionController {

    public static final String API_KEY = "QWnc4Z6Jkr2AJbx44pKviuwi";
    public static final String SECRET_KEY = "ButKrU610e16qNReGBQ5RCInpYCE6cBV";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @PostMapping("/plantRecognition")
    public ResponseResult getPlantRecognitionResult(@org.springframework.web.bind.annotation.RequestBody Map<String,String> imgPath){
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
        System.out.println(imgPath);
        try {
            // 要识别图片的文件路径
            String filePath = imgPath.get("recognitionImgPath");

            if (filePath==null){
                return new ResponseResult(404,"找不到图片路径",null);
            }else if((filePath.contains("http")||filePath.contains("https"))){
                //图片路径下载到本地更换路径
                URL url3 = new URL(filePath);
                System.out.println("url3:"+url3);
                URLConnection connection = url3.openConnection();
                InputStream inputStream = connection.getInputStream();
                String[] split = filePath.split("/");
                Integer split_len = split.length;
                String projectDirectory = new File("").getAbsolutePath(); // 获取当前项目的根目录
                String destinationFile=projectDirectory+"/fileDirectory/"+ split[split_len-1];
                // 创建一个文件输出流来保存下载的数据
                FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

                // 从输入流读取数据并写入文件输出流
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }

                // 关闭流
                inputStream.close();
                fileOutputStream.close();

//        -----end
                //修改url为本地文件路径
                filePath=destinationFile;
                System.out.println("filePath--1"+filePath);
                //end
            }
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            String accessToken = "[调用鉴权接口获取的token]";
            String accessToken = getAccessToken();

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
//            return result;
            //删除下载的图片
            Path path = Paths.get(filePath);
            Files.delete(path);
            return new ResponseResult(200,"植物识别成功",result);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500,"识别错误",null);
        }

    }
public static void m(String urlJoin) throws IOException {
    URL url3 = new URL(urlJoin);
    System.out.println("url3:"+url3);
    URLConnection connection = url3.openConnection();
    InputStream inputStream = connection.getInputStream();
    String[] split = urlJoin.split("/");
    Integer split_len = split.length;
    String projectDirectory = new File("").getAbsolutePath(); // 获取当前项目的根目录
    String destinationFile=projectDirectory+"/fileDirectory/"+ split[split_len-1];
    // 创建一个文件输出流来保存下载的数据
    FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

    // 从输入流读取数据并写入文件输出流
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        fileOutputStream.write(buffer, 0, bytesRead);
    }

    // 关闭流
    inputStream.close();
    fileOutputStream.close();

//        -----end
    //修改url为本地文件路径
    urlJoin=destinationFile;
    System.out.println("urlJoin--1"+urlJoin);
    //获取后缀文件格式
//    FORMAT=urlJoin.substring(urlJoin.length() - 3);
//    System.out.println("urlJoin--2"+urlJoin);
}

    public static void main(String[] args) throws IOException {
        m("https://img.shetu66.com/2022/11/04/1667538924331217.jpg");
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY+"&image=");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");


    }

}
